from robot.api import logger
from selenium.webdriver import ActionChains

from .PageElement import PageElement
from ...exception.TestException import TestException
from ...exception.errorcode import ErrorCode


class Canvas(PageElement):
    def click(self, left_percent, top_percent):
        x_percent = left_percent if isinstance(left_percent, (int, float)) else float(left_percent)
        y_percent = top_percent if isinstance(top_percent, (int, float)) else float(top_percent)

        self.wait_element_presence()
        element = self._get_web_element()

        if not element.location_once_scrolled_into_view:
            raise TestException.by_error_code(ErrorCode.ELEMENT_NO_VISIBLE)

        element_size = element.size
        x = (x_percent * element_size['width']) // 100
        y = (y_percent * element_size['height']) // 100
        logger.info("Canvas size {0}, offset left={1}, top={2}".format(element_size, x, y))
        ActionChains(self._driver).move_to_element_with_offset(element, x, y).click().perform()

    def get_identification(self):
        id = {'tag': ['canvas']}
        return id
